// 封装购物车模块
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import {useUserStore} from './user'
import {insertCartAPI,getCartAPI,delCartAPI} from '@/api/cart'
export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed( () => {
        return userStore.userInfo.token
    })
  const cartList = ref([])
  // 增加购物车
  const addCart = async (goods) => {
    const {skuId,count} = goods
    if(isLogin){
        // 登录
        await insertCartAPI({skuId,count})
        const res = await getCartAPI()
        cartList.value = res
    }else{
        // 匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
    const item = cartList.value.find((item) => goods.skuId === item.skuId)
    if (item) {
      item.count += goods.count
    } else {
      cartList.value.push(goods)
    }
    ElMessage.success('添加购物车成功')
    }
  }
  // 删除购物车
  const deleteCart = async (skuId) => {
   if(isLogin){
        await delCartAPI([skuId])
        const res = await getCartAPI()
        cartList.value = res
   }else{
    const index = cartList.value.findIndex((item) => item.skuId === skuId)
    if (index !== -1) {
      cartList.value.splice(index, 1)
      ElMessage.warning('删除商品成功')
    }
   }
  }
  // 清空购物车
  const clearCart = async () => {
    cartList.value = []
  }

  //计算总价
  const totalPrice = computed( () => 
    cartList.value.reduce( (sum, ele) => sum + ele.count * ele.price, 0)
  ) 
  // 计算商品总数
  const totalCount = computed(() => 
    cartList.value.reduce((sum, ele) => sum + ele.count, 0)
   )

   // 单选功能
   const singleCheck = (skuId,selected) => {
        const item = cartList.value.find( (item) => 
            item.skuId === skuId 
        )
        item.selected = selected
   }
   // 全选
   const allCheck = computed(() => {
    return cartList.value.every( item => item.selected)
   })
   const allCheck2 = (state) => {
     cartList.value.forEach( item => item.selected = state)
   }
   // 已选择数量
   const selectedCount = computed(() => {
        return cartList.value.filter( item => item.selected).reduce( (sum,ele) => sum + ele.count, 0)
   })
   // 已选择的总价
    const selectedTotalPrice = computed(() => {
     return cartList.value.filter( item => item.selected).reduce( (sum,ele) => sum + ele.count * ele.price, 0)
    })
  return {
    cartList,
    addCart,
    deleteCart,
    totalPrice,
    totalCount,
    singleCheck,
    allCheck,
    allCheck2,
    selectedCount,
    selectedTotalPrice,
    clearCart
  }
}, {
  persist: true,
})